import {createRouter, createWebHistory} from 'vue-router'
import Home from '../views/Home.vue'
import store from '@/store'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [
            {
                path: '/about',
                name: 'About',
                // route level code-splitting
                // this generates a separate chunk (about.[hash].js) for this route
                // which is lazy-loaded when the route is visited.
                meta: {
                    title: "搬砖银"
                },
                component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
            },
            {
                path: '/main',
                name: 'Main',
                // route level code-splitting
                // this generates a separate chunk (about.[hash].js) for this route
                // which is lazy-loaded when the route is visited.
                meta: {
                    title: "搬砖银"
                },
                component: () => import(/* webpackChunkName: "about" */ '../views/Main.vue')
            },
            {
                path: '/personCenter',
                name: 'PersonCenter',
                // route level code-splitting
                // this generates a separate chunk (about.[hash].js) for this route
                // which is lazy-loaded when the route is visited.
                meta: {
                    title: "搬砖银"
                },
                component: () => import(/* webpackChunkName: "about" */ '../views/PersonCenter.vue')
            },
        ],
        meta: {
            title: "搬砖银"
        },
    },


    {
        path: '/login',
        name: 'Login',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        meta: {
            title: "搬砖银入坑指南"
        },
        component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue'),
    }
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
});


router.beforeEach(async (to, from, next) => {
    if (to.meta.title) {//判断是否有标题
        document.title = to.meta.title
    }

    if (to.path === '/login') {
        next()
    } else {
        if (store.state.token) {
            next()
        } else {
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    }
});

export default router
